/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.authorization.manager.impl;

import com.alibaba.fastjson.JSONObject;
import com.bifrost.authorization.interceptor.AuthorizationInterceptor;
import com.bifrost.authorization.manager.TokenManager;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author joewee
 * @version 1.0.0
 * @Date 2018/5/19 15:47
 */
@Component
public class DefaultTokenManager implements TokenManager {
    private static final Logger logger = LoggerFactory.getLogger(DefaultTokenManager.class);
    private final Map<String,String> tokenMap = new ConcurrentHashMap<String,String>();
    @Value("${jwt.token.key}")
    private String key;

    @Value("${jwt.token.expire}")
    private Long expire;

    /**
     * 创建一个token关联上指定用户
     *
     * @param userId 指定用户的id
     * @return 生成的token
     */
    @Override
    public String createToken(long userId) {
        long nowMillis = System.currentTimeMillis();
        JSONObject payload = new JSONObject();
        payload.put("uid", userId);
        payload.put("scope", "ALL");
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder()
                .setIssuedAt(now)
                .setSubject(payload.toJSONString())
                .setIssuer("MALL")
                .signWith(SignatureAlgorithm.HS256, key);
        //Builds the JWT and serializes it to a compact, URL-safe string
        String token = builder.compact();
        tokenMap.put(""+userId,token);
        return token;
    }

    /**
     * 检查token是否有效,有效时则将id存入request
     *
     * @param token   待验证的token
     * @param request
     * @return 是否有效
     */
    @Override
    public boolean checkToken(String token, HttpServletRequest request) {
        if (token == null) {
            return false;
        }
        try {
            String s = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject();
            JSONObject json = JSONObject.parseObject(s);
            if (json.containsKey(AuthorizationInterceptor.UID)) {
                long uid = json.getLong(AuthorizationInterceptor.UID);
                request.setAttribute(AuthorizationInterceptor.UID, uid);
                return true;
            } else {
                return false;
            }
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 从字符串中解析token
     *
     * @param authentication 加密后的字符串
     * @return
     */
    @Override
    public String getToken(String authentication) {
        throw new UnsupportedOperationException();
    }

    /**
     * 清除token
     *
     * @param userId 登录用户的id
     */
    @Override
    public void deleteToken(long userId) {
        throw new UnsupportedOperationException();
    }
}
